package cn.wildfire.chat.app.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.king.zxing.Intents;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.ManumotiveIBinder;
import com.sourcemuch.im.caiba.R;
import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.SuperService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import cn.wildfire.chat.app.extendsion.classes.CheckVersionReq;
import cn.wildfire.chat.app.extendsion.classes.FriendRequestFromSource;
import cn.wildfire.chat.app.extendsion.classes.Textual;
import cn.wildfire.chat.app.extendsion.ui.LightThenNotifyPhone;
import cn.wildfire.chat.app.extendsion.ui.MainMenuPopupWindow;
import cn.wildfire.chat.app.extendsion.ui.PushNotifyImpl;
import cn.wildfire.chat.app.extendsion.ui.SmoothToggleAndSlideAnimationForUI;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.IMServiceStatusViewModel;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.WfcScheme;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.channel.ChannelInfoActivity;
import cn.wildfire.chat.kit.contact.ContactListFragment;
import cn.wildfire.chat.kit.contact.ContactViewModel;
import cn.wildfire.chat.kit.contact.newfriend.SearchUserActivity;
import cn.wildfire.chat.kit.conversation.CreateConversationActivity;
import cn.wildfire.chat.kit.conversationlist.ConversationGroupListFragment;
import cn.wildfire.chat.kit.conversationlist.ConversationGroupListViewModel;
import cn.wildfire.chat.kit.conversationlist.ConversationListFragment;
import cn.wildfire.chat.kit.conversationlist.ConversationListViewModel;
import cn.wildfire.chat.kit.conversationlist.ConversationListViewModelFactory;
import cn.wildfire.chat.kit.group.GroupInfoActivity;
import cn.wildfire.chat.kit.qrcode.ScanQRCodeActivity;
import cn.wildfire.chat.kit.search.SearchActivity;
import cn.wildfire.chat.kit.search.SearchGroupPortalActivity;
import cn.wildfire.chat.kit.search.SearchPortalActivity;
import cn.wildfire.chat.kit.user.UserInfoActivity;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfire.chat.kit.widget.ViewPagerFixed;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import q.rorbin.badgeview.QBadgeView;

/**
 * Create by HEKE, 2019/8/21 12:20
 * TODO 程序主界面
 */
public class MainActivity extends WfcBaseActivity implements ViewPager.OnPageChangeListener {

    private List<Fragment> mFragmentList = new ArrayList<>(4);

    @BindView(R2.id.bottomNavigationView)
    BottomNavigationView bottomNavigationView;
    @BindView(R2.id.contentViewPager)
    ViewPagerFixed contentViewPager;
    @BindView(R2.id.startingTextView)
    TextView startingTextView;
    @BindView(R2.id.contentLinearLayout)
    LinearLayout contentLinearLayout;

    private QBadgeView unreadMessageUnreadBadgeView;
    private QBadgeView unreadFriendRequestBadgeView;
    private QBadgeView unreadGroupMessageUnreadBadgeView;

    private static final int REQUEST_CODE_SCAN_QR_CODE = 100;
    private static final int REQUEST_IGNORE_BATTERY_CODE = 101;

    private IMServiceStatusViewModel imServiceStatusViewModel;
    private boolean isInitialized = false;

    private ConversationListFragment conversationListFragment;
    private ContactListFragment contactListFragment;
    private ConversationGroupListFragment conversationGroupListFragment;
    private MeFragment meFragment;

    private Observer<Boolean> imStatusLiveDataObserver = status -> {
        if (status && !isInitialized) {
            init();
            isInitialized = true;
        }
    };

    @Override
    protected int contentLayout() {
        return R.layout.main_activity;
    }

    /**
     * 首页触摸效果实现
     */
    protected SmoothToggleAndSlideAnimationForUI smoothToggleAndSlideAnimationForUI;

    @Override
    protected void afterViews() {
        setToolbarOrReplaceType(true, 0);
        setReplaceTitle(null, R.string.message_title);
        // IM连接信息通道监听、连接防护服务
        imServiceStatusViewModel = WfcUIKit.getAppScopeViewModel(IMServiceStatusViewModel.class);
        imServiceStatusViewModel.imServiceStatusLiveData().observeForever(imStatusLiveDataObserver);
        connectSuperService();
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        // 设置触摸效果控制对象
        smoothToggleAndSlideAnimationForUI = new SmoothToggleAndSlideAnimationForUI(this, SmoothToggleAndSlideAnimationForUI.FLAG_MAIN);
        smoothToggleAndSlideAnimationForUI.setToggleView(getSearchLayout());
        // 初次安装登入时，解决连接网络卡顿问题
        String firstOnInstallApp = SPUtils.getSingle(this, "foia", "app");
        if (!TextUtils.isTextEmpty(firstOnInstallApp) && firstOnInstallApp.equals("false")) {
            SPUtils.setSingle(this, "foia", "app", "true");
            if (mHandler != null) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        conversationListFragment.refreshConversations();
                    }
                }, 2000);
            }
        }
    }

    /**
     * 菜单弹窗
     */
    protected MainMenuPopupWindow mainMenuPopupWindow;

    @Override
    public void replaceMoreClicked() {
        try {
            if (mainMenuPopupWindow == null) {
                mainMenuPopupWindow = new MainMenuPopupWindow(MainActivity.this);
            }
            mainMenuPopupWindow.show(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 持续监听接口
     */
    private SuperService.OnCaiBaPersistentListener onCaiBaPersistentListener = new SuperService.OnCaiBaPersistentListener() {

        @Override
        public void alive(int seconds) {
            Log.i("ChatIM", "Entity...");
        }

        @Override
        public void refreshObserversReq() {
            if (contactListFragment != null) {
                contactListFragment.refreshFriendRequestSignWithAppNoNotufyPermission();
            }
            if (conversationListFragment != null) {
                conversationListFragment.refreshNotify();
            }
            if (conversationGroupListFragment != null) {
                conversationGroupListFragment.refreshNotify();
            }
        }

    };

    /**
     * modify by HEKE , 2019/8/20 19:18
     * TODO 增加前台服务，提升程序后台活性
     */
    private void connectSuperService() {
        try {
            ((CaiBaChatApp) getApplicationContext()).setMainActivityContext(MainActivity.this);
            caiBaChatApp.lightThenNotifyPhone = new LightThenNotifyPhone(this);
            Intent intent = new Intent(MainActivity.this, SuperService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent);
            } else {
                startService(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/8/20 20:34
     * TODO 绑定服务监听
     */
    public void bindListener() {
        SuperService.CaibaBinder caibaBinder = caiBaChatApp.caibaBinder;
        if (caibaBinder != null) {
            caibaBinder.bindPushObject(caiBaChatApp.wfcUIKit);
            caibaBinder.bindListener(onCaiBaPersistentListener);
        }
    }

    /**
     * modify by HEKE , 2019/8/24 15:32
     * TODO 具体处理手机推送信息实现函数
     */
    public void receiveMessage(String message, int type) {
        try {
            if (caiBaChatApp.isScreenLocked) {
                new PushNotifyImpl(this, message, type);
            }
            Log.e("###### receiveMessage ", "type : " + type + "  message : " + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/8/24 15:32
     * TODO IM通知
     */
    public void receiveMessage(String message, String title) {
        try {
            new PushNotifyImpl(this, message, title);
            Log.e("###### receiveMessage ", "title : " + title + "  message : " + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        new CheckVersionReq(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mHandler != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initListener();
                }
            }, 200);
        }
    }


    @Override
    protected void onDestroy() {
        manumotiveIBinder.release();
        super.onDestroy();
        imServiceStatusViewModel.imServiceStatusLiveData().removeObserver(imStatusLiveDataObserver);
    }

    /**
     * 群组刷新监听
     */
    protected ConversationGroupListViewModel conversationListViewModel2;

    public ConversationGroupListViewModel getConversationListViewModel2() {
        return conversationListViewModel2;
    }

    private void init() {
        initListener();
        initView();
        if (checkDisplayName()) {
            ignoreBatteryOption();
        }

        //ll
        Toast.makeText(this, "捕捉到一个错误,请联系开发", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 刷新监听
     */
    private void initListener() {
        /**
         * modify by HEKE , 2019/9/7 14:27 TODO 单聊信息走旧版本单例VM模式
         */
        ConversationListViewModel conversationListViewModel = ViewModelProviders
                .of(this, new ConversationListViewModelFactory(Arrays.asList(Conversation.ConversationType.Single), Arrays.asList(0)))
                .get(ConversationListViewModel.class);
        conversationListViewModel.unreadCountLiveData().observe(this, unreadCount -> {

            if (unreadCount != null && unreadCount.unread > 0) {
                showUnreadMessageBadgeView(unreadCount.unread);
            } else {
                hideUnreadMessageBadgeView();
            }
        });

        /**
         * modify by HEKE , 2019/9/7 14:27 TODO 群组信息新建VM模式
         */
        if (conversationListViewModel2 == null) {
            conversationListViewModel2 = ViewModelProviders
                    .of(this, new ConversationListViewModelFactory(Arrays.asList(Conversation.ConversationType.Group), Arrays.asList(0)))
                    .get(ConversationGroupListViewModel.class);
            manumotiveIBinder.bindObject(ManumotiveIBinder.GROUP_LIST_VIEWMODEL, conversationListViewModel2);
        }
        conversationListViewModel2.unreadCountLiveData().observe(this, unreadCount -> {
            if (unreadCount != null && unreadCount.unread > 0) {
                showUnreadGroupMessageBadgeView(unreadCount.unread);
            } else {
                hideUnreadGroupMessageBadgeView();
            }
        });

        ContactViewModel contactViewModel = WfcUIKit.getAppScopeViewModel(ContactViewModel.class);
        contactViewModel.friendRequestUpdatedLiveData().observe(this, count -> {
            if (count == null || count == 0) {
                hideUnreadFriendRequestBadgeView();
            } else {
                showUnreadFriendRequestBadgeView(count);
            }
        });
    }

    private void showUnreadMessageBadgeView(int count) {
        try {
            if (unreadMessageUnreadBadgeView == null) {
                BottomNavigationMenuView bottomNavigationMenuView = ((BottomNavigationMenuView) bottomNavigationView.getChildAt(0));
                View view = bottomNavigationMenuView.getChildAt(0);
                unreadMessageUnreadBadgeView = new QBadgeView(MainActivity.this);
                unreadMessageUnreadBadgeView.bindTarget(view);
                if (unreadMessageUnreadBadgeView != null) {
                    int viewWidth = getBottomItemWidth();
                    unreadMessageUnreadBadgeView.setBadgeGravity(Gravity.START | Gravity.TOP);
                    unreadMessageUnreadBadgeView.setGravityOffset(viewWidth / 2 + 28, 2, false);
                }
            }
            unreadMessageUnreadBadgeView.setBadgeNumber(count);
            if (count > 99) {
                unreadMessageUnreadBadgeView.setBadgeText("...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showUnreadGroupMessageBadgeView(int count) {
        try {
            if (unreadGroupMessageUnreadBadgeView == null) {
                BottomNavigationMenuView bottomNavigationMenuView = ((BottomNavigationMenuView) bottomNavigationView.getChildAt(0));
                View view = bottomNavigationMenuView.getChildAt(2);
                unreadGroupMessageUnreadBadgeView = new QBadgeView(MainActivity.this);
                unreadGroupMessageUnreadBadgeView.bindTarget(view);
                if (unreadGroupMessageUnreadBadgeView != null) {
                    int viewWidth = getBottomItemWidth();
                    unreadGroupMessageUnreadBadgeView.setBadgeGravity(Gravity.START | Gravity.TOP);
                    unreadGroupMessageUnreadBadgeView.setGravityOffset(viewWidth / 2 + 28, 2, false);
                }
            }
            unreadGroupMessageUnreadBadgeView.setBadgeNumber(count);
            if (count > 99) {
                unreadGroupMessageUnreadBadgeView.setBadgeText("...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hideUnreadMessageBadgeView() {
        if (unreadMessageUnreadBadgeView != null) {
            unreadMessageUnreadBadgeView.hide(true);
            unreadFriendRequestBadgeView = null;
        }
    }

    private void hideUnreadGroupMessageBadgeView() {
        if (unreadGroupMessageUnreadBadgeView != null) {
            unreadGroupMessageUnreadBadgeView.hide(true);
            unreadGroupMessageUnreadBadgeView = null;
        }
    }

    private void showUnreadFriendRequestBadgeView(int count) {
        try {
            if (unreadFriendRequestBadgeView == null) {
                BottomNavigationMenuView bottomNavigationMenuView = ((BottomNavigationMenuView) bottomNavigationView.getChildAt(0));
                View view = bottomNavigationMenuView.getChildAt(1);
                unreadFriendRequestBadgeView = new QBadgeView(MainActivity.this);
                unreadFriendRequestBadgeView.bindTarget(view);
                if (unreadFriendRequestBadgeView != null) {
                    int viewWidth = getBottomItemWidth();
                    unreadFriendRequestBadgeView.setBadgeGravity(Gravity.START | Gravity.TOP);
                    unreadFriendRequestBadgeView.setGravityOffset(viewWidth / 2 + 28, 2, false);
                }
            }
            unreadFriendRequestBadgeView.setBadgeNumber(count);
            contactListFragment.updateRequestFriendValue(count);
            if (count > 99) {
                unreadFriendRequestBadgeView.setBadgeText("...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/8/29 11:45 获取底部菜单栏各项的宽度
     */
    private int getBottomItemWidth() {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        return screenWidth / mFragmentList.size();
    }

    public void hideUnreadFriendRequestBadgeView() {
        if (unreadFriendRequestBadgeView != null) {
            unreadFriendRequestBadgeView.hide(true);
            unreadFriendRequestBadgeView = null;
        }
    }

    @Override
    protected int menu() {
        return R.menu.main;
    }

    @Override
    protected boolean showHomeMenuItem() {
        return false;
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    private void initView() {
        startingTextView.setVisibility(View.GONE);
        contentLinearLayout.setVisibility(View.VISIBLE);
        //设置ViewPager的最大缓存页面
        contentViewPager.setOffscreenPageLimit(3);

        conversationListFragment = new ConversationListFragment();
//        contactListFragment = new ContactListFragment();
//        conversationGroupListFragment = new ConversationGroupListFragment();
        meFragment = new MeFragment();
        mFragmentList.add(conversationListFragment);
//        mFragmentList.add(contactListFragment);
//        mFragmentList.add(conversationGroupListFragment);
        mFragmentList.add(meFragment);

        contentViewPager.setAdapter(new HomeFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList));
        contentViewPager.setOnPageChangeListener(this);
        contentViewPager.setCanScroll(false);

        manumotiveIBinder.bindObject(ManumotiveIBinder.PAGE_SINGLE, conversationListFragment);
//        manumotiveIBinder.bindObject(ManumotiveIBinder.PAGE_CONTACT, contactListFragment);
//        manumotiveIBinder.bindObject(ManumotiveIBinder.PAGE_GROUP, conversationGroupListFragment);
        manumotiveIBinder.bindObject(ManumotiveIBinder.PAGE_ME, meFragment);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.conversation_list) {
                contentViewPager.setCurrentItem(Textual.TYPE_CONVERSATION);
                setShowIndex(Textual.TYPE_CONVERSATION);
                setTouchSpecailSet(true);
                manumotiveIBinder.RefreshPageDatas(Textual.TYPE_CONVERSATION, 200);
            } else if (itemId == R.id.contact) {
                contentViewPager.setCurrentItem(Textual.TYPE_CONTACT);
                setShowIndex(Textual.TYPE_CONTACT);
                setTouchSpecailSet(true);
                manumotiveIBinder.RefreshPageDatas(Textual.TYPE_CONTACT, 200);
            } else if (itemId == R.id.group_conversation_list) {
                contentViewPager.setCurrentItem(Textual.TYPE_GROUP_CONVERSATION);
                setShowIndex(Textual.TYPE_GROUP_CONVERSATION);
                setTouchSpecailSet(true);
                manumotiveIBinder.RefreshPageDatas(Textual.TYPE_GROUP_CONVERSATION, 200);
            } else if (itemId == R.id.me) {
                contentViewPager.setCurrentItem(Textual.TYPE_ME);
                setShowIndex(Textual.TYPE_ME);
                setTouchSpecailSet(false);
                manumotiveIBinder.RefreshPageDatas(Textual.TYPE_ME, 200);
            }
            return true;
        });
        bottomNavigationView.setItemIconTintList(null);
        setTouchSpecailSet(true);
    }

    /**
     * Popup窗口点击选择操作
     *
     * @param id
     */
    public void onOptionsClicked(int id) {
        if (id == R.id.qunliaoLayout) {
            createConversation();
        } else if (id == R.id.addFriendLayout) {
            searchUser();
        } else if (id == R.id.saoyisaoLayout) {
            qrscan();
        }
    }

    /**
     * 扫一扫
     */
    private void qrscan() {
        String[] permissions = new String[]{Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!checkPermission(permissions)) {
                requestPermissions(permissions, 100);
                return;
            }
        }
        /**
         * 设置添加好友来源于扫码
         * */
        FriendRequestFromSource.setFromsource(FriendRequestFromSource.ADD_FROM_QRCODE);
        startActivityForResult(new Intent(this, ScanQRCodeActivity.class), REQUEST_CODE_SCAN_QR_CODE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.search) {
            showSearchPortal();
        } else if (itemId == R.id.chat) {
            createConversation();
        } else if (itemId == R.id.add_contact) {
            searchUser();
        } else if (itemId == R.id.scan_qrcode) {
            qrscan();
        }
        return super.onOptionsItemSelected(item);
    }

    private void showSearchPortal() {
        Intent intent = new Intent(this, SearchPortalActivity.class);
        intent.putExtra("search_type", SearchActivity.TYPE_MORE_SEARCH);
        startActivity(intent);
    }

    private void showGroupSearchPortal() {
        Intent intent = new Intent(this, SearchGroupPortalActivity.class);
        intent.putExtra("search_type", SearchActivity.TYPE_MORE_SEARCH);
        startActivity(intent);
    }

    private void showSearchContact() {
        Intent intent = new Intent(this, SearchContactActivity.class);
        intent.putExtra("search_type", SearchActivity.TYPE_CONTACT_SEARCH);
        startActivity(intent);
    }

    private void createConversation() {
        Intent intent = new Intent(this, CreateConversationActivity.class);
        startActivity(intent);
    }

    private void searchUser() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        intent.putExtra("search_type", SearchActivity.TYPE_USER_SEARCH);
        intent.putExtra("style", "add_friend");
        startActivity(intent);
    }

    @Override
    protected void onSearChLayoutClick() {
        super.onSearChLayoutClick();
        if (type == Textual.TYPE_CONTACT) {
            showSearchContact();
        } else if (type == Textual.TYPE_CONVERSATION) {
            showSearchPortal();
        } else if (type == Textual.TYPE_GROUP_CONVERSATION) {
            showGroupSearchPortal();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case Textual.TYPE_CONVERSATION:
                bottomNavigationView.setSelectedItemId(R.id.conversation_list);
                smoothToggleAndSlideAnimationForUI.setSlideView(null, type);
                break;
            case Textual.TYPE_CONTACT:
                bottomNavigationView.setSelectedItemId(R.id.contact);
                smoothToggleAndSlideAnimationForUI.setSlideView(null, type);
                break;
            case Textual.TYPE_GROUP_CONVERSATION:
                bottomNavigationView.setSelectedItemId(R.id.group_conversation_list);
                smoothToggleAndSlideAnimationForUI.setSlideView(null, type);
                break;
            case Textual.TYPE_ME:
                bottomNavigationView.setSelectedItemId(R.id.me);
                break;
            default:
                break;
        }
        setShowIndex(position);
        contactListFragment.showQuickIndexBar(position == 1);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state != ViewPager.SCROLL_STATE_IDLE) {
            //滚动过程中隐藏快速导航条
            contactListFragment.showQuickIndexBar(false);
        } else {
            contactListFragment.showQuickIndexBar(true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SCAN_QR_CODE:
                if (resultCode == RESULT_OK) {
                    String result = data.getStringExtra(Intents.Scan.RESULT);
                    onScanPcQrCode(result);
                }
                break;
            case REQUEST_IGNORE_BATTERY_CODE:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(this, "允许后台运行，更能保证消息的实时性", Toast.LENGTH_SHORT).show();
                }
                break;
            case 1007:
                // 刷新联系人及会话界面
                if (type == Textual.TYPE_CONTACT) {
                    if (contactListFragment != null) {
                        contactListFragment.loadContacts(true);
                    }
                } else if (type == Textual.TYPE_CONVERSATION) {
                    if (conversationListFragment != null) {
                        conversationListFragment.refreshConversations();
                    }
                } else if (type == Textual.TYPE_GROUP_CONVERSATION) {
                    if (conversationGroupListFragment != null) {
                        conversationGroupListFragment.refreshConversations();
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startActivityForResult(new Intent(this, ScanQRCodeActivity.class), REQUEST_CODE_SCAN_QR_CODE);
        }
    }

    private void onScanPcQrCode(String qrcode) {
        String prefix = qrcode.substring(0, qrcode.lastIndexOf('/') + 1);
        String value = qrcode.substring(qrcode.lastIndexOf("/") + 1);
        switch (prefix) {
            case WfcScheme.QR_CODE_PREFIX_PC_SESSION:
                pcLogin(value);
                break;
            case WfcScheme.QR_CODE_PREFIX_USER:
                showUser(value);
                break;
            case WfcScheme.QR_CODE_PREFIX_GROUP:
                joinGroup(value);
                break;
            case WfcScheme.QR_CODE_PREFIX_CHANNEL:
                subscribeChannel(value);
                break;
            default:
                Toast.makeText(this, "qrcode: " + qrcode, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void pcLogin(String token) {
        Intent intent = new Intent(this, PCLoginActivity.class);
        intent.putExtra("token", token);
        startActivity(intent);
    }

    private void showUser(String uid) {
        UserViewModel userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        UserInfo userInfo = userViewModel.getUserInfo(uid, true);
        if (userInfo == null) {
            return;
        }
        Intent intent = new Intent(this, UserInfoActivity.class);
        intent.putExtra("userInfo", userInfo);
        boolean isMyFriend = ChatManager.Instance().isMyFriend(userInfo.uid);
        intent.putExtra("commonGroupLayoutShow", isMyFriend);
        startActivityForResult(intent, 1007);
    }

    private void joinGroup(String groupId) {
        Intent intent = new Intent(this, GroupInfoActivity.class);
        intent.putExtra("groupId", groupId);
        startActivity(intent);
    }

    private void subscribeChannel(String channelId) {
        Intent intent = new Intent(this, ChannelInfoActivity.class);
        intent.putExtra("channelId", channelId);
        startActivity(intent);
    }

    @Deprecated
    private boolean checkDisplayName() {
        return true;
    }

    /**
     * 提醒电池高消耗，不需要此项提醒
     */
    private void ignoreBatteryOption() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                Intent intent = new Intent();
                String packageName = getPackageName();
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
                    startActivityForResult(intent, REQUEST_IGNORE_BATTERY_CODE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*************************************************************************************
     * TODO 触摸层顶层事件处理  Add by HEKE 20190911-10:02
     *************************************************************************************/
    protected boolean touchSpecailSet;

    public void setTouchSpecailSet(boolean touchSpecailSet) {
        this.touchSpecailSet = touchSpecailSet;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            /**
             * 主界面需要触摸事件特殊处理的标记，其他情况直接下传
             * */
            if (touchSpecailSet) {
                if (smoothToggleAndSlideAnimationForUI != null) {
                    if (smoothToggleAndSlideAnimationForUI.isSlideViewNull()) {
                        if (type == Textual.TYPE_CONVERSATION) {
                            smoothToggleAndSlideAnimationForUI.setSlideView(conversationListFragment.getView().findViewById(R.id.recyclerView), type);
                        } else if (type == Textual.TYPE_CONTACT) {
                            smoothToggleAndSlideAnimationForUI.setSlideView(contactListFragment.getView().findViewById(R.id.usersRecyclerView), type);
                        } else if (type == Textual.TYPE_GROUP_CONVERSATION) {
                            smoothToggleAndSlideAnimationForUI.setSlideView(conversationGroupListFragment.getView().findViewById(R.id.recyclerView), type);
                        }
                    }
                    smoothToggleAndSlideAnimationForUI.onTouchEvent(ev);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.dispatchTouchEvent(ev);
    }

}
